﻿using System;
using System.Net;
using System.IO;
using System.Xml;

namespace FilesTubeDAL
{
    public class RSDAL
    {
        /// <summary>
        /// Key to the FilesTube API
        /// </summary>
        public string FtKey { get; set; }
        public string FtUrl { get; set; }
        public string SearchUrl { get; set; }
        
        public RSDAL()
        {
            FtKey = "dad56b56afdbfaca9e577716786d7c26";
            FtUrl = "http://api.filestube.com/?key=" + FtKey + "&phrase=";
            SearchUrl = "http://www.filestube.com/search.html?select=All&hosting=1&q=";
        }

        /// <summary>
        /// Connects to FilesTube API and gets search results
        /// </summary>
        /// <param name="search">Search parameter string</param>
        /// <returns>Array of RSResult objects or null if error</returns>
        public RsResult[] GetSearchResults(string search)
        {
            var ub = new UriBuilder(FtUrl + search);
            var uri = Uri.EscapeUriString(ub.Uri.ToString());
            var res = GetPage(uri);

            try
            {
                var xml = new XmlDocument();
                xml.LoadXml(res);
                var hitsCount = xml.GetElementsByTagName("hits").Count;

                if (hitsCount > 0)
                {
                    var rsresults = new RsResult[hitsCount];
                    var rCounter = 0;

                    foreach (XmlElement hit in xml.GetElementsByTagName("hits"))
                    {
                        rsresults[rCounter] = new RsResult
                                                    {
                                                        Name = hit.SelectSingleNode("name").InnerText,
                                                        Extension = hit.SelectSingleNode("extension").InnerText,
                                                        Size = hit.SelectSingleNode("size").InnerText,
                                                        Description = hit.SelectSingleNode("description").InnerText,
                                                        Link = new Uri(hit.SelectSingleNode("address").InnerText),
                                                        DetailsLink = new Uri(hit.SelectSingleNode("details").InnerText),
                                                        Added = DateTime.Parse(hit.SelectSingleNode("added").InnerText),
                                                        Password = hit.SelectSingleNode("password").InnerText
                                                    };
                        rCounter++;
                    }

                    return rsresults;
                }

                return null;
            }
            catch (XmlException e)
            {
                return null;    
            }
        }

        /// <summary>
        /// Gets HTML page from server
        /// </summary>
        /// <param name="url">URL of the page to get</param>
        /// <returns>String of HTML source</returns>
        protected string GetPage(string url)
        {
            WebResponse response = null;
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                response = request.GetResponse();
                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                    return null;

                string buffer = "", line;
                reader = new StreamReader(stream);

                while ((line = reader.ReadLine()) != null)
                {
                    buffer += line + "\r\n";
                }

                return buffer;
            }
            catch (WebException e)
            {
                Console.WriteLine("Can't download:" + e);
                return null;
            }
            catch (IOException e)
            {
                Console.WriteLine("Can't download:" + e);
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();

                if (stream != null)
                    stream.Close();

                if (response != null)
                    response.Close();
            }
        }
    }
}

